var sys = require('sys');
var queue = require('./queue');

exports.create = function(playerPool, gamePool) {
  return new QueuePool(playerPool, gamePool);
}

function QueuePool(playerPool, gamePool) {
  this.queueList = [];
  this.playerPool = playerPool;
  this.gamePool = gamePool;
  
  sys.log("QueuePool:construct Creating new playerpool");
  
  this.update = function() {
    
  }
  
  this.contains = function(id) {
    return (this.get(id));
  }
  
  this.get = function(id) {
    for(var i = 0; i < this.queueList.length; i++)
    {
      if(this.queueList[i].contains(id))
        return this.queueList[i];
    }

    return null;
  }
  
  // This is called whenever a new player has entered the playerpool
  this.newPlayerInPool = function(newPlayer) {
    sys.log("QueuePool:newPlayerInPool:event");
    
    // Iterate the current queue list and find the first one that isn't full
    for(var i = 0; i < this.queueList.length; i++)
    {
      if(this.queueList[i].size() < this.queueList[i].maxPlayers)
      {
        this.queueList[i].add(newPlayer);
        this.playerPool.remove(newPlayer.id);
        newPlayer.movedToQueue(this.queueList[i]);
        
        if(this.queueList[i].full())
          this.queueHasBecomeFull(this.queueList[i]);
        
        break;
      }
    }
    
    // Still here? No available space in the queue list
    // create a new queue
    var newQueue = queue.create();
    this.queueList.push(newQueue);
    newQueue.add(newPlayer);
    this.playerPool.remove(newPlayer.id);
    newPlayer.movedToQueue(newQueue);
    if(newQueue.full())
      this.queueHasBecomeFull(newQueue);
  }
  
  this.queueHasBecomeFull = function(queue) {
    sys.log("QueuePool:queueHasBecomeFull:event");
    
    // Create a new game from the full queue
    //this.playerPool.createFrom(queue);
    
    var self = this;
    queue.startCountdown();
    queue.countdownFinished = function() {
      self.gamePool.createFrom(queue);
    
      // Destroy the queue, and remove from the list
      for(var i = 0; i < self.queueList.length; i++)
      {
        if(self.queueList[i] == queue)
          self.queueList.remove(i);
      }
    }
  }
}